import Token from "../../shared/models/token";
import AuthenticationService from "../../shared/services/authentication-service";
import TokenService from "../../shared/services/token-service";
import AuthService from "./auth-service";

// 获取应用实例
// const app = getApp<IAppOption>();

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName'), // 如需尝试获取用户信息可改为false
  },
  // 事件处理函数
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs',
    });
  },
  onLoad() {
    // @ts-ignore
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true,
      });
    }

    var user = {
      name: 'Dolly',
    };

    var sprintf = require('sprintf-js').sprintf;

    console.log(sprintf('Hello %(name)s', user));
  },
  getUserProfile() {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res);

        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        });
      }
    })
  },
  getUserInfo(e: any) {
    // 不推荐使用getUserInfo获取用户信息，预计自2021年4月13日起，getUserInfo将不再弹出弹窗，并直接返回匿名的用户个人信息
    console.log(e);

    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true,
    });
  },
  async login(): Promise<void> {
    // if (!isAuthenticated) {
    const authCode = await AuthService.sendAuthCode({
      username: '17702197245',
      type: 'AUTHENTICATION',
    });

    const res = await AuthService.login('17702197245', authCode);

    if (res?.accessToken) {
      // Gets the server data to user instance.
      // const user = User.fromJson(res);

      // Saves the user data retrieved from server.
      AuthenticationService.saveUserInfo(res);

      // Gets the server data to token instance.
      const token = await Token.fromServerJson(res);

      // Saves the token data retrieved from server.
      TokenService.saveToken(token);
    }
    // } else {
    //   AuthenticationService.removeUserInfo();
    //   TokenService.removeToken();
    // }

    // dispatch(change(AuthenticationService.isAuthenticated));
  },
  async testApi(): Promise<void> {
    let i = 0

    while (i < 10) {
      const res = await AuthService.testApi({ pageIndex: 0, pageSize: 2 });
      console.log(res);

      i++;
    }
  },
});